<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <link rel="icon" href="data:,">
  <title>WebSocket</title>
</head>
<body>
<input type="text" id="url" size="50" value="ws://127.0.0.1:8080/chat?name=zhangsan">
<button onclick="openWs(url.value)">open</button>
<button onclick="closeWs()">close</button>
<p></p>
<form onsubmit="return false">
  <textarea name="message" style="height: 300px; width: 300px">hello</textarea>
  <input type="button" value="send" onclick="send(this.form.message.value)">

  <textarea id="responseText" style="height: 300px; width: 300px" readonly></textarea>
  <input type="button" value="empty" onclick="document.getElementById('responseText').value=''">
</form>

<script>
  let ws, rt = document.getElementById("responseText");

  function openWs(url) {
    if (window.WebSocket) {
      if (ws && ws.readyState === WebSocket.OPEN) ws.close();
      ws = new WebSocket(url);
      ws.onmessage = event => rt.value += event.data + "\n"; // 接收数据回调
      ws.onopen = () => console.info(ws);// 连接建立成功回调
      ws.onerror = event => console.error(event); // 连接失败回调
      ws.onclose = event => console.info(event); // 连接关闭回调
    } else {
      alert('当前浏览器不支持 WebSocket');
    }
  }

  function send(message) { // 发送消息到服务器
    if (ws && ws.readyState === WebSocket.OPEN) ws.send(message);
    else alert("未连接");
  }

  closeWs = () => ws.close();
</script>
</body>
</html>